package cn.lbf.stuniversity.shiro.service;

import cn.lbf.stuniversity.constant.Code;
import cn.lbf.stuniversity.shiro.dao.UserDao;
import cn.lbf.stuniversity.shiro.entity.User;
import cn.lbf.stuniversity.utils.ResultUtil;
import cn.lbf.stuniversity.vo.Result;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public Result<Map<String,Object>> login(User u) {
        User user1 = userDao.login(u.getUsername());
        if (user1 != null && bcryptCheck(user1.getPassword(), u.getPassword())) {
            return new ResultUtil<Map<String, Object>>().setSuccessMsg("添加成功");
        }else {
            return new ResultUtil<Map<String, Object>>().setErrorMsg(Code.FAIL, "添加失败，请联系管理员!");
        }
    }

    //加密所有的数据库账户的密码
    public void migratePasswords() {
        List<User> users = userDao.findAllUsers();
        for (User user : users) {
            String encryptedPassword = bcryptHash(user.getPassword());
            user.setPassword(encryptedPassword);
            userDao.updatePassword(user.getUsername(), encryptedPassword);
        }
    }

    private String bcryptHash(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }

    private boolean bcryptCheck(String password, String hashedPassword) {
        return BCrypt.checkpw(password, hashedPassword);
    }
}
